package org.redis.cluster.test.transport.netty;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
	
	private int port;

	public NettyServer(int port) {
		this.port=port;
	}
	
	public void start() throws Exception {
		EventLoopGroup bossGroup=new NioEventLoopGroup(1);
		EventLoopGroup workerGroup=new NioEventLoopGroup(1);
        
    	ServerBootstrap serverBootstrap=new ServerBootstrap();
		serverBootstrap.group(bossGroup,workerGroup);
		serverBootstrap.channel(NioServerSocketChannel.class);
		
		serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel socketChannel) throws Exception {
				ChannelPipeline pipeline=socketChannel.pipeline();
				pipeline.addLast("decoder", new TestDecoder());  
		        pipeline.addLast("encoder", new NettyEncoder());  
		        pipeline.addLast("handler", new NettyHandler());
			}
		});
		
		ChannelFuture channelFuture=serverBootstrap.bind(new InetSocketAddress(port)).sync();
	}
}